<template>
    <div id="wk_monitor">
      <div class="right-map">
        <div style="height: 100%">
          <el-amap class="amap-box" :amap-manager="amapManager" :events="events" :zoom="zoom" :vid="'amap-vue'">
            <div class="left-box">
              <div class="page-header">
                <span class="title-item">车辆监控</span>
                <span class="countdown">{{ timers }}s后刷新</span>
              </div>
              <div class="title-box">
                车辆实时列表
              </div>
              <div class="waterfall-wrapper">
                <a-directory-tree multiple default-expand-all :show-line="false" :show-icon="false">
                  <a-tree-node key="0-0">
                    <div slot="title">在线<span style="color: #bebebe">({{offlineTotal }}辆)</span></div>
                    <a-tree-node v-for="(item, i) in offlineList" :key="i">
                      <template>
                        <div @click="selectFn(item)" slot="title">{{ item.carCode }}</div>
                      </template>
                    </a-tree-node>
                  </a-tree-node>
                  <a-tree-node key="0-1">
                    <div slot="title">离线<span style="color: #bebebe">({{ onlineTotal }}辆)</span></div>
                    <a-tree-node v-for="item in onlineList" :key="item.carCode">
                      <template>
                        <div @click="selectFn(item)" slot="title">
                          {{ item.carCode }}
                        </div>
                      </template>
                    </a-tree-node>
                  </a-tree-node>
                </a-directory-tree>
              </div>
            </div>
          </el-amap>
        </div>
        <div class="widow-box" ref="infoWindow" v-show="isinfoWindow">
          <h3 class="h3">
            {{ code }}
            <a-icon class="guanbiicon" type="close-circle" @click="closeInfoWindow"/>
          </h3>
          <ul>
            <li class="single">
              <p class="single-title">车辆速度:</p>
              <p class="single-cent">{{ details.speed }}km/h</p>
            </li>
            <li class="single">
              <p class="single-title">定位时间:</p>
              <p class="single-cent">
                {{ moment.unix(details.gpsTime).format("YYYY-MM-DD HH:mm:ss") }}
              </p>
            </li>
            <li class="single">
              <p class="single-title">最后通信:</p>
              <p class="single-cent">
                {{ moment.unix(details.heartTime).format("YYYY-MM-DD HH:mm:ss") }}
              </p>
            </li>
            <li class="single">
              <p class="single-title">车辆状态:</p>
              <p class="single-cent" v-if="details.deviceInfo == 0">在线</p>
              <p class="single-cent" v-if="details.deviceInfo == 3">离线</p>
              
            </li>
          </ul>
        </div>
      </div>
    </div>
</template>

<script>
import moment from "moment";
import "moment/locale/zh-cn";
import { AMapManager, lazyAMapApiLoaderInstance } from "vue-amap";
import { log } from "video.js";
var x_PI = (3.14159265358979324 * 3000.0) / 180.0;
var PI = 3.1415926535897932384626;
var a = 6378245.0;
var ee = 0.00669342162296594323;
let amapManager = new AMapManager(); // 新建生成地图画布
export default {
  name: "index",

  data() {
    let self = this;
    return {
      code: "", //信息框显示的车牌号
      form: {
        //获取车辆信息
        imeis: [],
        accessToken: "",
      },
      target: "13770618954",
      carForm: {
        //全部拉取
        currentPage: 1,
        pageSize: 1000,
        userId: this.$user.id,
      },
      carList: [], //汽车列表（获取imie号）

      offlineTotal: "",
      onlineTotal: "",
      markerArr: [], //标记的数组
      clickedMarker: "", // 已选中的点标记
      isinfoWindow: false, //  是否显示窗口
      details: {}, //信息框内容
      isimei: "", //选中车辆的imie号
      zuobiao: null, //转化过的坐标
      moment,
      selectShu: null,
      amapManager,
      mapStyle: "amap://styles/39ba2088b6b8fc67184833f73cceab4d",
      zoom: 10, //地图缩放等级
      map: "",
      events: {
        init(o) {
          lazyAMapApiLoaderInstance.load().then(() => {
            self.initPage();
          });
        },
      },
      carInfor: {}, //选中的数据
      countDown: "", //倒计时
      timers: 59,
      setTime: "", //定时器
      dataList: [], //实时数据
      onlineList: [], //在线列表
      onlineListA: [], //在线列表
      offlineList: [], //离线列表
      notlineList: [], //未上线列表
      expiredList: [], //过期列表
    };
  },
  methods: {
    //gps转高德
    wgstogcj02(lat, lng) {
      var out = new Array();
      var gg_lat, gg_lon;
      var dlat = this.transformlat(lng - 105.0, lat - 35.0);
      var dlng = this.transformlng(lng - 105.0, lat - 35.0);
      var radlat = (lat / 180.0) * PI;
      var magic = Math.sin(radlat);
      magic = 1 - ee * magic * magic;
      var sqrtmagic = Math.sqrt(magic);
      dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI);
      dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI);
      gg_lat = lat + dlat;
      gg_lon = lng + dlng;
      out[0] = gg_lat;
      out[1] = gg_lon;
      return out;
    },
    transformlat(lng, lat) {
      var ret =
        -100.0 +
        2.0 * lng +
        3.0 * lat +
        0.2 * lat * lat +
        0.1 * lng * lat +
        0.2 * Math.sqrt(Math.abs(lng));
      ret +=
        ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) *
          2.0) /
        3.0;
      ret +=
        ((20.0 * Math.sin(lat * PI) + 40.0 * Math.sin((lat / 3.0) * PI)) *
          2.0) /
        3.0;
      ret +=
        ((160.0 * Math.sin((lat / 12.0) * PI) +
          320 * Math.sin((lat * PI) / 30.0)) *
          2.0) /
        3.0;
      return ret;
    },

    transformlng(lng, lat) {
      var ret =
        300.0 +
        lng +
        2.0 * lat +
        0.1 * lng * lng +
        0.1 * lng * lat +
        0.1 * Math.sqrt(Math.abs(lng));
      ret +=
        ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) *
          2.0) /
        3.0;
      ret +=
        ((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) *
          2.0) /
        3.0;
      ret +=
        ((150.0 * Math.sin((lng / 12.0) * PI) +
          300.0 * Math.sin((lng / 30.0) * PI)) *
          2.0) /
        3.0;
      return ret;
    },

    //实时获取token
    gettoken() {
      this.$api.getCarToken().then((res) => {
        this.form.accessToken = res.data.data.accessToken;
      });
    },
    //选中车辆方法
    selectFn(item, i) {
      console.log(item);
      this.deviceInfo = item.deviceInfo
      this.code = item.carCode;
      this.carInfor = item;
      this.isimei = item.imei;
      this.markerArr.forEach((item, index) => {
        if(this.deviceInfo == 0){
            if (item.getExtData().imei == this.isimei) {
          this.se;
          if (this.clickedMarker) {
            this.clickedMarker.setIcon(
              new AMap.Icon({
                image: require("@/assets/public/car.png"),
                size: new AMap.Size(52, 26), //图标大小
                imageSize: new AMap.Size(52 * 0.7, 26 * 0.7),
              })
            );
          }
          item.setIcon(
            new AMap.Icon({
              size: new AMap.Size(52, 26),
              image: require("@/assets/public/car.png"),
              imageSize: new AMap.Size(52, 26),
              imageOffset: new AMap.Pixel(0, 0),
            })
          );
          this.clickedMarker = item;
          if (!i) {
            console.log("hei");
            this.map.setCenter(item.getPosition());
          }
        }
        }else{
            if (item.getExtData().imei == this.isimei) {
          this.se;
          if (this.clickedMarker) {
            this.clickedMarker.setIcon(
              new AMap.Icon({
                image: require("@/assets/public/car1.png"),
                size: new AMap.Size(52, 26), //图标大小
                imageSize: new AMap.Size(52 * 0.7, 26 * 0.7),
              })
            );
          }
          item.setIcon(
            new AMap.Icon({
              size: new AMap.Size(52, 26),
              image: require("@/assets/public/car1.png"),
              imageSize: new AMap.Size(52, 26),
              imageOffset: new AMap.Pixel(0, 0),
            })
          );
          this.clickedMarker = item;
          if (!i) {
            console.log("hei");
            this.map.setCenter(item.getPosition());
          }
        }
        }

      });
      this.carList.forEach((v, i) => {
        if (v.imei == item.imei) {
          this.selectShu = v;
          this.details = this.carList[i];
        }
      });
      this.openinfoWindow(this.selectShu);
    },

    //点击搜索按钮方法
    showCont() {
      // getCarDetail
      this.$api.getCarList(this.carForm).then((res) => {
        console.log(res);
        this.carList = res.data.data.records;
        console.log(this.carList);
        // let mapList = new Map();
        let onlineTotal = 0,
          offlineTotal = 0;
        this.carList.forEach((item) => {
          if (item.deviceInfo == 0) {
            offlineTotal++;
          } else {
            onlineTotal++;
          }
          if (item.deviceInfo == 0) {
            this.offlineList.push(item);
          }
          if (item.deviceInfo == 3) {
            this.onlineList.push(item);
          }
          // console.log(item);
          // mapList.set(item.imei, item);
          // this.form.imeis.push(item.imei);
          this.offlineTotal = offlineTotal;
          this.onlineTotal = onlineTotal;
        });
        this.markerList();
        // 通过imie号查找数据
        // this.$api.getCarLocation(this.form).then((res) => {
        //   this.dataList = res.data.data.data;
        //   console.log();
        //   this.dataList.forEach((item) => {
        //     console.log(item);
        //     let _item = mapList.get(item.imei);
        //     item.carCode = _item.carCode;
        //     if (item.device_info == 0) {
        //       this.onlineList.push(item);
        //     }
        //     if (item.device_info == 3) {
        //       this.offlineList.push(item);
        //     }
        //     if (item.device_info == 1) {
        //       this.notlineList.push(item);
        //     }
        //     if (item.device_info == 2) {
        //       this.expiredList.push(item);
        //     }
        //   });
        //   this.markerList();
        // });
      });
    },

    //初始化地图方法
    initPage() {
      this.map = this.amapManager.getMap();
    },

    //渲染多点
    markerList() {
      // this.map.remove(this.markerArr);
      // this.map.clearMap();
      //清除过期小车
      // this.dataList.forEach((item, index) => {
      //   if (item.device_info == 2) {
      //     this.dataList.splice(index, 1);
      //   }
      // });
      //建立小车图标
      this.carList.forEach((item) => {
        // this.zuobiao = this.wgstogcj02(parseInt(item.lat), parseInt(item.lng));

        let icon = "";
        if (item.deviceInfo == 3) {
          icon = new AMap.Icon({
            size: new AMap.Size(52, 26),
            image: require("@/assets/public/car1.png"),
            imageSize: new AMap.Size(52 * 0.8, 26 * 0.8),
            imageOffset: new AMap.Pixel(0, 0),
          });
        } else {
           icon = new AMap.Icon({
            size: new AMap.Size(52, 26),
            image: require("@/assets/public/car.png"),
            imageSize: new AMap.Size(52 * 0.8, 26 * 0.8),
            imageOffset: new AMap.Pixel(0, 0),
          });
        }
        if(item.id == "1302812462834290689"){
          console.log(item.lng)
          console.log(item.lat)
        }
        let marker = new AMap.Marker({
          position: new AMap.LngLat(item.lng, item.lat),
          icon: icon,
          title: this.carList.areaName,
        });
        marker.setExtData({ imei: item.imei });
        AMap.event.addListener(marker, "click", (e) => {
          this.selectFn(item, "1");
          if (this.carInfor !== {}) {
            setTimeout(() => {
              this.selectFn(this.carInfor, "1");
            }, 1000);
          }
          this.openinfoWindow(item);
          this.clickedMarker = e.target;
        });
        this.markerArr.push(marker);
        console.log(this.markerArr);
      });
      if (this.carInfor == {}) {
        this.map.setFitView();
      }
      this.map.add(this.markerArr);
    },

    // 创建标签方法
    createInfoWindow(data) {
      this.isinfoWindow = true;
      return this.$refs.infoWindow;
    },
    // 打开标签方法
    openinfoWindow(data) {
      if (data) {
        var position = new AMap.LngLat(data.lng, data.lat);
        this.infoWindow.setContent(this.createInfoWindow(data));
        this.infoWindow.open(this.map, position);
      }
      // this.map.panTo(position);
    },
    // 关闭窗口方法
    closeInfoWindow() {
      this.map.clearInfoWindow();
    },
    //清空数据
    clearList() {
      this.timers = 59;
      this.dataList = [];
      this.map.remove(this.markerArr);
      this.markerArr = [];
      this.carList = [];
      this.onlineList = []; //在线列表
      this.offlineList = []; //离线列表
      this.notlineList = []; //未上线列表
      this.expiredList = []; //过期列表
      this.showCont();
      if (this.carInfor !== {}) {
        var timerT = setTimeout(() => {
          this.selectFn(this.carInfor);
        }, 500);
      }
    },
  },

  //把全局的背景图片取消
  mounted() {
    //每过一分钟刷新数据
    this.setTime = setInterval(() => {
      this.clearList();
    }, 5000 * 12);
    //页面右上角倒计时
    this.countDown = setInterval(() => {
      this.timers--;
      if (this.timers < 0) {
        this.timers = 0;
      }
    }, 1000);
    setTimeout(() => {
      this.showCont();
    }, 1000);
    this.gettoken();
    //创建信息框
    this.infoWindow = new AMap.InfoWindow({
      isCustom: true,
      anchor: "middle-left",
      offset: new AMap.Pixel(40, -10),
    });
    document
      .querySelector(".box-content")
      .classList.add("none-background");
  },

  //离开时清除定时器
  beforeDestroy() {
    clearInterval(this.setTime);
    clearInterval(this.countDown);
  },
  beforeRouteLeave(to, from, next) {
    document
      .querySelector(".box-content")
      .classList.remove("none-background");
    next();
  },
};
</script>

<style scoped lang="scss">
//右边整体
#wk_monitor {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  .left-box {
    height: 80%;
    width: 20%;
    box-sizing: border-box;
    position: absolute;
    top: 4%;
    left: 4%;
    z-index: 5;
    background: #fff;
    box-shadow: 0 0 10px 0 rgba(0,0,0,0.3);
    border-radius: 10px;
    .page-header{
      width: 100%;
      padding: 0 16px;
      line-height: 50px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title-item{
        font-size: 18px;
        color: #000;
        font-weight: 700;
      }
      .countdown {
        color: #1890ff;
      }
    }
    .title-box{
      width: 100%;
      height: 28px;
      font-size: 14px;
      line-height: 28px;
      background: #deefff;
      padding: 0 16px;
    }
    .waterfall-wrapper {
      width: calc(100% - 24px) ;
      margin: 12px;
      height: calc(100% - 100px);
      overflow-y: auto;
      overflow-x: hidden;
      //&::-webkit-scrollbar{
      //  overflow: hidden;
      //}
    }
  }
  .right-map {
    height: 100%;
    width: 100%;
    box-sizing: border-box;
    position: relative;
  }
}


.submit-box {
  margin-top: 20px;
  float: right;
  .sdefault-btn {
    margin: 0 20px;
  }
}
// 信息窗体样式
.widow-box {
  width: 270px;
  height: auto;
  padding: 10px;
  box-sizing: border-box;
  border-radius: 10px;
  background: #fff;
  position: relative;
  .guanbiicon {
    font-size: 24px;
    float: right;
  }
  .single {
    width: 100%;
    height: auto;
    display: flex;
    .single-title {
      width: 40%;
      // text-align: right;
    }
    .single-cent {
      width: 65%;
      //color: #258cd7;
    }
  }
}
.back-btn {
  position: absolute;
  top: -180px;
  left: 420px;
  font-size: 30px;
  cursor: pointer;
}
//车辆查询
.car-list {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 10px 100px 10px 15px;

  .car-address {
    flex: 1;
    padding-left: 15px;

  }
}

::v-deep .ant-form-item-label label {
  color: #9fb043;
  font-size: 18px;
}

::v-deep .ant-form-item-children input {
  background-color: #29423f;
  border: none;
  color: #bebebe;
}

::v-deep .ant-btn:hover,
::v-deep .ant-btn:focus,
::v-deep .ant-btn:active,
::v-deep .ant-btn.active {
  text-decoration: none;
  background: #37ddc0;
}

::v-deep .ant-form-item {
  margin-right: 0px;
  width: 100%;
}

::v-deep .ant-form-item-label {
  width: 22%;
}

::v-deep .ant-form-item-control-wrapper {
  width: 78%;
}

::v-deep .ant-row {
  margin-bottom: 6px;
}

::v-deep .layout-content-main {
  background: none !important;
}

::v-deep .ant-pagination-item,
::v-deep .ant-select-selection {
  background-color: #1e3230;
  border: none;
}

::v-deep .ant-pagination-item a,
::v-deep .ant-select-arrow,
::v-deep .ant-select-selection__rendered {
  color: #bebebe;
}

::v-deep .ant-pagination-prev .ant-pagination-item-link,
::v-deep .ant-pagination-next .ant-pagination-item-link {
  background-color: #1e3230;
  border: none;
  color: #bebebe;
}

::v-deep .ant-pagination-total-text {
  color: #bebebe;
}

::v-deep .scroll {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 2rem; //预留foot组件
  overflow: hidden;
}

.amap-box {
  width: 100%;
  height: 100%;
}
</style>
